package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"new_ginblog/internal/models"
	"new_ginblog/internal/repositories"
	"new_ginblog/internal/utils/errormsg"
	"strconv"
)

var (
	artStatusCode int
)

// AddArticle 增加文章
func AddArticle(c *gin.Context) {
	var article models.Article
	_ = c.ShouldBindJSON(&article)
	artStatusCode = repositories.AddArticle(&article)
	c.JSON(http.StatusOK, gin.H{
		"code": artStatusCode,
		"msg":  errormsg.GetErrorMsg(artStatusCode),
		"data": article,
	})
}

// GetArticle 获取指定文章
func GetArticle(c *gin.Context) {
	var article models.Article
	id, _ := strconv.Atoi(c.Param("id"))
	article, artStatusCode = repositories.GetArticle(id)
	if artStatusCode == errormsg.ERROR {
		c.JSON(http.StatusOK, gin.H{
			"code": artStatusCode,
			"msg":  errormsg.GetErrorMsg(artStatusCode),
		})
		return
	} else if artStatusCode == errormsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H{
			"code": artStatusCode,
			"msg":  errormsg.GetErrorMsg(artStatusCode),
			"data": article,
		})
	}
}

// GetArticleList 获取分类下的全部文章
func GetArticleList(c *gin.Context) {
	var articles []models.Article
	var total int64
	var category string
	cid, _ := strconv.Atoi(c.Param("cid"))
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageNum == 0 {
		pageNum = -1
	}
	if pageSize == 0 {
		pageSize = -1
	}
	articles, category, artStatusCode, total = repositories.GetArticleList(cid, pageSize, pageNum)
	if artStatusCode == errormsg.ERROR {
		c.JSON(http.StatusOK, gin.H{
			"code":     artStatusCode,
			"msg":      errormsg.GetErrorMsg(artStatusCode),
			"total":    total,
			"category": category,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":  artStatusCode,
		"msg":   errormsg.GetErrorMsg(artStatusCode),
		"total": total,
		"data":  articles,
	})
}

// DeleteArticle 删除文章
func DeleteArticle(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	artStatusCode = repositories.DeleteArticle(id)
	c.JSON(http.StatusOK, gin.H{
		"code": artStatusCode,
		"msg":  errormsg.GetErrorMsg(artStatusCode),
	})
}

// UpdateArticle 修改文章
func UpdateArticle(c *gin.Context) {
	var article *models.Article
	var id int
	_ = c.ShouldBindJSON(&article)
	id, _ = strconv.Atoi(c.Param("id"))
	artStatusCode = repositories.UpdateArticle(id, article)
	c.JSON(http.StatusOK, gin.H{
		"code": artStatusCode,
		"msg":  errormsg.GetErrorMsg(artStatusCode),
		"data": article,
	})
}
